<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产商名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产商名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间选择" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          style="width:333px;"
          :default-time="['00:00:00','23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:nbPlugCard:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list">
      <el-table-column label="产商名称" align="center" prop="name" />
      <el-table-column label="数量" align="center" prop="amount"  />
      <el-table-column label="已用数量" align="center" prop="useAmount" />
      <el-table-column label="剩余数量" align="center" prop="remainAmount" />
      <el-table-column label="有效期" align="center" prop="expireTime" />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="购买时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
            v-hasPermi="['system:nbPlugCard:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(row)"
            v-hasPermi="['system:nbPlugCard:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handlemingxi(row)"
            v-hasPermi="['system:nbPlugCardDetail:list']"
          >明细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <div v-if="title == '明细'">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="mxHandleAdd"
              v-hasPermi="['system:nbPlugCardDetail:add']"
            >新增</el-button>
          </el-col>
          <right-toolbar @queryTable="listNBPlugCardDetailController"></right-toolbar>
        </el-row>
        <el-table v-loading="mxLoading" :data="mxList">
          <el-table-column label="划拨数量" align="center" prop="amount"  />
          <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
          <el-table-column label="划拨时间" align="center" prop="createTime" />
          <el-table-column label="操作人" align="center" prop="operator" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="mxHandleUpdate(row)"
                v-hasPermi="['system:nbPlugCardDetail:edit']"
              >修改</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="mxTotal>0"
          :total="mxTotal"
          :page.sync="mxQueryParams.pageNum"
          :limit.sync="mxQueryParams.pageSize"
          @pagination="listNBPlugCardDetailController"
        />
      </div>
      <el-form v-else ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="卡商" prop="cardMerchantId">
          <el-select v-model="form.cardMerchantId" :disabled="form.id ? true : false" placeholder="请选择卡商">
            <el-option
              v-for="item1 in kashangList"
              :key="item1.id"
              :label="item1.name"
              :value="item1.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="amount">
          <el-input-number v-model="form.amount" :step="1" step-strictly :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="有效时间" prop="expireTime">
          <el-date-picker
            v-model="form.expireTime"
            type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择有效时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="购买时间" prop="createTime">
          <el-date-picker
            v-model="form.createTime"
            type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择购买时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea" :rows="6" placeholder="请输入备注" v-model="form.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="title != '明细'" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="mxTitle" :visible.sync="mxOpen" width="60%" append-to-body>
      <el-form ref="mxForm" :model="mxForm" :rules="mxRules" label-width="80px">
        <el-form-item label="剩余">
          {{ showselectList.remainAmount }}
        </el-form-item>
        <el-form-item label="划拨数量" prop="amount">
          <el-input-number v-model="mxForm.amount" :step="1" step-strictly :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :rows="6" placeholder="请输入备注" v-model="mxForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="mxSubmitForm">确 定</el-button>
        <el-button @click="mxOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, addPage, editPage, delPage,
  listNBPlugCardDetailController,addNBPlugCardDetailController,editNBPlugCardDetailController,} from "@/api/deviceNBCardManag/plugUnpCardMage";
import { getAllNBCardMerchant,  } from "@/api/deviceNBCardManag/cardMerchManage";
import { math,  } from "@/utils/math";
export default {
  name: "PlugUnpCardMage",
  dicts: ['project_push_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      mxLoading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      mxTotal: 0,
      // 表格数据
      list: [],
      mxList: [],
      // 弹出层标题
      title: "",
      mxTitle: "",
      // 是否显示弹出层
      open: false,
      mxOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        dateRange:[],
      },
      mxQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      mxForm: {},
      // 表单校验
      rules: {
        cardMerchantId: [{ required: true, message: "卡商不能为空", trigger: "change" }],
        amount: [{ required: true, message: "数量不能为空", trigger: "blur" }],
        expireTime: [{ required: true, message: "有效时间不能为空", trigger: "change" }],
        createTime: [{ required: true, message: "购买时间不能为空", trigger: "change" }],
      },
      mxRules: {
        amount: [{ required: true, message: "数量不能为空", trigger: "blur" }],
        remark: [{ required: true, message: "备注不能为空", trigger: "blur" }],
      },
      kashangList:[],//卡商数据
      selectList:{},//原始选中的列表数据
      showselectList:{},//显示选中的列表数据
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handlemingxi(e){//获取明细
      this.selectList = {...e}
      this.showselectList = {...e}
      this.reset();
      this.open = true;
      this.title = "明细";
      this.mxQueryParams.cardId = e.id
      this.listNBPlugCardDetailController()
    },
    async listNBPlugCardDetailController(){//NB插拔卡明细数据分页获取
      this.mxLoading = true;
      let res = await listNBPlugCardDetailController(this.mxQueryParams)
      this.mxList = res.rows || [];
      this.mxTotal = res.total || 0;
      this.mxLoading = false;
    },
    async getAllNBCardMerchant(){//获取卡商
      let res = await getAllNBCardMerchant()
      let data = res.data || []
      this.kashangList = data
    },
    /** 查询字典类型列表 */
    async getList() {
      this.loading = true;
      let queryParams = {...this.queryParams}
      let dateRange = this.queryParams.dateRange || []
      if(dateRange.length) {
        queryParams.startTime = dateRange[0]
        queryParams.endTime = dateRange[1]
      }
      delete queryParams.dateRange
      let response = await getList(queryParams)
      this.list = response.rows || [];
      this.total = response.total || 0;
      this.loading = false;
      return response.rows
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
      this.getAllNBCardMerchant()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加插拔卡管理";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      this.form = {...row,};
      this.open = true;
      this.title = "修改插拔卡管理";
    },
    getStrNull(str){//判断是否为空
      return str === '' || str === null || str === undefined
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let form = {...this.form}
          if (this.form.id != undefined) {
            editPage(form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPage(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return delPage(dictIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 表单重置
    mxReset() {
      this.mxForm = {};
      this.resetForm("mxForm");
    },
    /** 新增按钮操作 */
    mxHandleAdd() {
      this.showselectList = {...this.selectList}
      this.mxReset();
      this.mxOpen = true;
      this.mxTitle = "添加明细";
    },
    /** 修改按钮操作 */
    async mxHandleUpdate(row) {
      let showselectList = {...this.selectList}
      showselectList.remainAmount = math.add(Number(showselectList.remainAmount),Number(row.amount))
      this.showselectList = {...showselectList}
      this.mxReset();
      this.mxForm = {...row,};
      this.mxOpen = true;
      this.mxTitle = "修改明细";
    },
    /** 提交按钮 */
    mxSubmitForm: function() {
      this.$refs["mxForm"].validate(valid => {
        if (valid) {
          let mxForm = {...this.mxForm}
          if(Number(mxForm.amount) > Number(this.showselectList.remainAmount)) return this.$modal.msgError("明细数量不能大于剩余数量");
          if (this.mxForm.id != undefined) {
            editNBPlugCardDetailController(mxForm).then(async response => {
              this.$modal.msgSuccess("修改成功");
              this.mxOpen = false;
              this.listNBPlugCardDetailController();
              let list = await this.getList()
              let obj = list.find(item=>item.id == this.selectList.id)
              if(obj) this.selectList = {...obj}
            });
          } else {
            mxForm.cardId = this.mxQueryParams.cardId
            addNBPlugCardDetailController(mxForm).then(async response => {
              this.$modal.msgSuccess("新增成功");
              this.mxOpen = false;
              this.listNBPlugCardDetailController();
              let list = await this.getList()
              let obj = list.find(item=>item.id == this.selectList.id)
              if(obj) this.selectList = {...obj}
            });
          }
        }
      });
    },
  }
};
</script>